<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import { getCurrentInstance, setStorage, setStorageSync, showToast } from '@tarojs/taro';
import getAuthCode from 'gdt-jsapi/getAuthCode';
import authConfig from 'gdt-jsapi/authConfig';
import { APP_EDITION } from '/@/common/constant';
import { DD_USER_LOGIN, DD_TOKEN_GET } from '/@/api/modules/ding-talk/dd-user';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { logInDev } from '/@/utils/index';
import HomeHgy from './components/home-hgy.vue';
import HomeJinhuaPoliceServiceLogistics from './components/jinhua-police-service/home-logistics.vue';
import HomeJinhuaPoliceServiceStaff from './components/jinhua-police-service/home-staff.vue';
import HomeCanNangThirdHospitalLogistics from './components/can-nang-third-hospital/home-logistics.vue';
import HomeCanNangThirdHospitalStaff from './components/can-nang-third-hospital/home-staff.vue';
import HomeLogistics from './components/default/home-logistics.vue';
import HomeStaff from './components/default/home-staff.vue';
import HOME_SCAN from '/@/assets/image/icon/home-scan.png';
import { scanMenu } from '/@/utils/scan';
/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 租户 ID
   */
  corpId?: string;
  /**
   * 授权码
   */
  auth_code?: string;
  /**
   * 授权码
   */
  code?: string;
};

const state = reactive<{
  /**
   * 应用版本
   */
  appEdition: keyof typeof APP_EDITION;
  /**
   * 当前登录权限编码（1-WEB端，2-后勤端，3-员工端）
   */
  currentRolePlatformCode: AppSysUserApi.LoginAppResp['currentRolePlatformCode'];
}>({
  appEdition: (process.env.APP_EDITION as keyof typeof APP_EDITION) || 'default',
  currentRolePlatformCode: 3,
});

/**
 * @function 钉钉用户登录
 * @param authCode
 */
function ddUserLogin(authCode: string) {
  DD_USER_LOGIN({ authCode })
    .then((res) => {
      setStorage({
        key: 'token',
        data: res.token,
        success: () => {
          setStorageSync('loginType', 'dg-work');

          LOGIN_APP().then((res) => {
            state.currentRolePlatformCode = res.currentRolePlatformCode;
          });
        },
      });
    })
    .catch((err) => {
      showToast({
        title: err.comResp.err || err.comResp.tip,
      });
    });
}

onMounted(() => {
  // 专有钉桌面客户端
  if (params.corpId && params.auth_code) {
    ddUserLogin(params.auth_code);
    return;
  }

  // 专有钉移动客户端
  if (params.corpId && !params.auth_code) {
    getAuthCode({
      corpId: params.corpId,
    }).then((res) => {
      logInDev({ function: 'getAuthCode', res });
      ddUserLogin(res.auth_code || res.code || '');
      getAuthCode({
        corpId: params.corpId,
      }).then((res) => {
        logInDev({ function: 'getAuthCode', res });
        DD_TOKEN_GET({
          authCode: res.auth_code || res.code || '',
        })
          .then((res) => {
            logInDev({ function: 'DD_TOKEN_GET', res });

            authConfig({
              ticket: res.tokenJsonDto.accessToken,
              jsApiList: ['onAudioPlayEnd'],
            })
              .then((res2) => {
                logInDev({ function: 'authConfig', res2 });
              })
              .catch((err2) => {
                logInDev({ function: 'authConfig', err2 });
              });
          })
          .catch((err) => {
            showToast({
              title: err.comResp.err || err.comResp.tip,
            });
          });
      });
    });

    return;
  }

  LOGIN_APP().then((res) => {
    state.currentRolePlatformCode = res.currentRolePlatformCode;
  });
});
</script>

<template>
  <view class="home app-page--1">
    <component
      v-if="state.appEdition === 'hgy'"
      :is="{ 2: HomeLogistics, 3: HomeHgy }[state.currentRolePlatformCode]"
    />
    <component
      v-else-if="['default'].includes(state.appEdition)"
      :is="{ 2: HomeLogistics, 3: HomeStaff }[state.currentRolePlatformCode]"
    />
    <component
      v-else-if="['jinhua-police-service'].includes(state.appEdition)"
      :is="
        { 2: HomeJinhuaPoliceServiceLogistics, 3: HomeJinhuaPoliceServiceStaff }[
          state.currentRolePlatformCode
        ]
      "
    />
    <component
      v-else-if="['can-nang-third-hospital'].includes(state.appEdition)"
      :is="
        { 2: HomeCanNangThirdHospitalLogistics, 3: HomeCanNangThirdHospitalStaff }[
          state.currentRolePlatformCode
        ]
      "
    />
    <view class="home__bottom">
      <app-tab-bar active="home" />
      <image
        :src="HOME_SCAN"
        class="home__bottom__image"
        @click="scanMenu()"
        v-if="['default'].includes(state.appEdition) && state.currentRolePlatformCode === 2"
      />
    </view>
  </view>
</template>
<style lang="scss">
.home {
  &__bottom {
    position: relative;

    &__image {
      position: absolute;
      top: -40px;
      left: 50%;
      transform: translate(-50%);
      width: 100px;
      height: 100px;
    }
  }
}
</style>
